//
//  JokeVC.m
//  renyikan
//
//  Created by Steven on 2019/7/16.
//  Copyright © 2019 Steven. All rights reserved.
//

#import "JokeVC.h"
#import "JokeCell.h"
@interface JokeVC ()
@property(nonatomic, strong)NSMutableArray *datas;
@end

@implementation JokeVC
{
    NSInteger _page;
    BOOL _isRefresh;
    
}

- (NSMutableArray *)datas{
    if (_datas == nil) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableFooterView = [UIView new];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 60;
    _page = 1;
    [self getWXDatasWithPage:_page];

    __weak typeof(self) weakSelf = self;
    [self.tableView pullRefresh:^{
        self->_isRefresh = NO;
        self->_page ++;
        [weakSelf getWXDatasWithPage:self->_page];
    }];
    
    [self.tableView downRefresh:^{
        self->_isRefresh = YES;
        self->_page = 1;
        [weakSelf getWXDatasWithPage:self->_page];
    }];

}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *data = self.datas[indexPath.row];
    JokeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JokeCell" forIndexPath:indexPath];
    cell.contentLabel.text = data[@"content"];
    cell.timeLabel.text = data[@"updatetime"];
    return cell;
}


- (void)getWXDatasWithPage:(NSInteger)page{
    
    __weak typeof(self) weakSelf = self;
    
    NSInteger time = (NSInteger)[NSDate new].timeIntervalSince1970;
    
    
    
    [JFNetworkingManager requestWithURLString: [NSString stringWithFormat:@"http://v.juhe.cn/joke/content/list.php?key=2480c635f72f8b907ce6699835de3071&page=%ld&pagesize=20&sort=dsc&time=%ld",(long)page, time] parameters:nil type: HttpRequestTypePost view: self.view success:^(id responseObject) {
        
        [weakSelf.tableView.mj_header endRefreshing];
        
        if (_isRefresh) {
            weakSelf.datas = responseObject[@"result"][@"data"];
        }else{
            [weakSelf.datas addObjectsFromArray:responseObject[@"result"][@"data"]];
            if ([responseObject[@"result"][@"data"] count] < 20) {
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                [weakSelf.tableView.mj_footer endRefreshing];
            }
        }
        [weakSelf.tableView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
}


@end
